package com.yupi.springbootinit.utils.file;

import lombok.extern.slf4j.Slf4j;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.util.List;

/**
 * @Author shxl2021
 * @Date 2023/8/14 9:58
 * @Version 1.0
 */
@Slf4j
public class FileCopy {
    private static final String path = "C:\\Users\\LENOVO\\AppData\\Roaming\\JetBrains\\IntelliJIdea2022.3\\scratches\\type-node\\方太分支合并\\test";

    public static void main(String[] args) throws Exception {
        List<String> list = FileRead.readFile(path, s -> 1);
        for (String s : list) {
            s = s.substring(s.indexOf("C:"));
            copyFile(s, s.replace("C:\\Datas\\E9\\9.00.2310\\", "C:\\Datas\\E9\\适配环境脚本\\"), true);
        }
    }

    public static boolean copyFile(String source, String target) {
        return copyFile(source, target, false);
    }

    /**
     * @param source 源文件
     * @param target 目标文件
     * @param cover 是否覆盖
     * @return 创建是否成功
     */
    public static boolean copyFile(String source, String target, boolean cover) {
        File targerFile = new File(target);
        if (targerFile.exists()) {
            if (cover) {
                targerFile.delete();
                log.info("目标文件已删除:::{}", target);
            } else {
                log.info("目标文件已存在:::{}", target);
                return false;
            }
        }
        File parentFile = targerFile.getParentFile();
        boolean mkdirs = parentFile.mkdirs();
        File sourceFile = new File(source);
        if (mkdirs) {
            log.trace("mkdir:success:{}",parentFile.getAbsolutePath());
        }
        try {
            Files.copy(sourceFile.toPath(), targerFile.toPath());
            log.info("文件复制完成：{}",target);
        } catch (IOException e) {
            log.error("文件复制异常\n" + source);
            throw new RuntimeException("目标文件不存在");
        }
        return true;
    }
}
